package com.kern.rpc.client;

import com.kern.rpc.bean.Request;
import com.kern.rpc.bean.Response;

import java.io.*;
import java.net.Socket;

/**
 * Created by caoshi at 20:22 2021-07-21
 */
public class RpcClient {

    private Socket sock;

    public RpcClient() {
    }

    public Object invoke(Request request, String ip, int port) throws IOException {
        sock = new Socket(ip, port);
        InputStream in = sock.getInputStream();
        OutputStream out = sock.getOutputStream();
        ObjectOutputStream objOut;
        ObjectInputStream objIn;
        Response response = null;
        try {
            objOut = new ObjectOutputStream(out);
            objOut.writeObject(request);
            objOut.flush();
            objIn = new ObjectInputStream(in);
            Object res = objIn.readObject();
            if (res instanceof Response) {
                response = (Response) res;
            } else {
                throw new RuntimeException("返回對象不正确!!!");
            }
        } catch (Exception e) {
            System.out.println("error:   " + e.getMessage());
        } finally {
            out.close();
            in.close();
            sock.close();
            return  response.getObj();
        }
    }




}
